package com.cee.admin.modules.sys.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cee.admin.common.BaseController;
import com.cee.common.core.query.BasePageQuery;
import com.cee.common.exception.GlobalException;
import com.cee.common.utils.VerifyUtils;
import com.cee.common.web.result.Result;
import com.cee.domain.modules.sys.entity.User;
import com.cee.domain.modules.sys.form.SysUserAddForm;
import com.cee.domain.modules.sys.form.SysUserUpdateForm;
import com.cee.domain.modules.sys.vo.LoginUser;
import com.cee.domain.modules.sys.vo.UserVo;
import com.cee.ds.modules.sys.service.IUserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static com.cee.common.web.result.ResultCode.USER_PASSWORD_PATTERN_ERROR;


/**
 * <p>
 * ϵͳ 前端控制器
 * </p>
 *
 * @author zcj
 * @since 2020-12-07
 */
@Tag(name = "系统用户管理")
@RestController
@RequestMapping("/api/v1/sys/user")
public class UserController extends BaseController {

    public static final String SAVE_OR_UPDATE = "saveOrUpdate";
    @Autowired
    private IUserService iUserService;

    @Operation(summary = "当前用户")
    @GetMapping("current")
    public Result<LoginUser> currentUser() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        user.setPassword(null);
        user.setSalt(null);
        LoginUser loginUser = iUserService.currentUser(user);
        return success(loginUser);
    }

    @Operation(summary = "分页查询")
    @GetMapping("/page")
    @RequiresPermissions("sys:user:select")
    public Result<Page<UserVo>> page(BasePageQuery<UserVo> query, Long roleId, String name, String mobileNumber, String loginName) {
        try {
            UserVo userVo = new UserVo();
            userVo.setRoleId(roleId);
            userVo.setName(name);
            userVo.setMobileNumber(mobileNumber);
            userVo.setLoginName(loginName);
            return success(iUserService.queryPageVo(query.generatePage(), userVo));
        } catch (Exception e) {
            log.error(e.getMessage());
            return error("系统错误，请联系管理员！");
        }
    }

    @Operation(summary = "用户列表")
    @GetMapping("list")
    @RequiresPermissions("sys:user:select")
    public Result<List<UserVo>> list() {
        try {
            return success(iUserService.listVo(new UserVo()));
        } catch (Exception e) {
            log.error(e.getMessage());
            return error("系统错误，请联系管理员！");
        }
    }

    @Operation(summary = "更新用户状态", description = "只需传id和status以及loginName")
    @PostMapping("status")
    @RequiresPermissions("sys:user:status:change")
    public Result<Boolean> changeStatus(@RequestBody UserVo userVo) {
        return success(iUserService.changeStatus(userVo));
    }

    @Operation(summary = "保存")
    @PostMapping("save")
    @RequiresPermissions(value = {"sys:user:save"})
    public Result<Long> save(@RequestBody SysUserAddForm addForm) {
        return success(iUserService.add(addForm));
    }

    @Operation(summary = "更新")
    @PostMapping("update")
    @RequiresPermissions(value = {"sys:user:update"})
    public Result<Long> update(@RequestBody SysUserUpdateForm updateForm) {
        return success(iUserService.update(updateForm));
    }



    /*
     * 获取角色数据，关联用户
     * */
    @Operation(summary = "获取角色数据，关联用户")
    @GetMapping("getUser")
    @RequiresPermissions("sys:user:select")
    public Result<UserVo> getUser(String id) {
        try {
            return success(iUserService.getUser(id));
        } catch (Exception e) {
            log.error(e.getMessage());
            return error("系统错误，请联系管理员！");
        }
    }

    /*
     * 检验账号是否存在
     * */
    @Operation(summary = "检验账号是否存在")
    @PostMapping("existsAccount")
    @RequiresPermissions(value = "sys:user:exist")
    public Result<Boolean> existsAccount(@RequestBody User user) {
        try {
            return success(iUserService.exists(user));
        } catch (Exception e) {
            log.error(e.getMessage());
            return error("系统错误，请联系管理员！");
        }
    }

    @DeleteMapping("/delete/{id}")
    @RequiresPermissions("sys:user:delete")
    @Operation(summary = "删除")
    public Result<Boolean> delete(@PathVariable("id") Long id) {
        return success(iUserService.deleteUserById(id));
    }


    @PostMapping("/updateMyPassword")
    @Operation(summary = "修改我的密码", description = "只需要新密码，key为password")
    public Result<Boolean> updatePassword(@RequestBody @Parameter(description = "password") Map<String, String> body) {
        String password = body.get("password");
        if (!VerifyUtils.checkPwd(password)) {
            throw new GlobalException(USER_PASSWORD_PATTERN_ERROR);
        }
        iUserService.updateMyPassword(password);
        return success(true);
    }


}

